﻿function Get-ExcelCellData {
    param (
        [Parameter(Mandatory=$true)]
        [string]$WorkbookPath,

        [Parameter(Mandatory=$true)]
        [string]$WorksheetName,

        [Parameter(Mandatory=$true)]
        [int]$Row,

        [Parameter(Mandatory=$true)]
        [int]$Column
    )

    # 加载Excel COM对象
    $excel = New-Object -ComObject Excel.Application

    # 设置Excel为不可见（不显示应用程序窗口）
    $excel.Visible = $false

    try {
        # 打开指定的Excel工作簿
        $workbook = $excel.Workbooks.Open($WorkbookPath)

        # 选择特定的工作表（可以通过名称或索引）
        $worksheet = $workbook.Sheets.Item($WorksheetName)

        # 获取特定单元格的数据
        $cellValue = $worksheet.Cells.Item($Row, $Column).Value2

        return $cellValue

    } catch {
        Write-Error "An error occurred while accessing the Excel file: $_"
        return $null
    } finally {
        # 关闭工作簿而不保存更改
        if ($workbook) {
            $workbook.Close($false)
        }

        # 退出Excel应用程序
        if ($excel) {
            $excel.Quit()
        }

        # 释放COM对象
        if ($worksheet) {
            [System.Runtime.Interopservices.Marshal]::ReleaseComObject($worksheet) | Out-Null
        }
        if ($workbook) {
            [System.Runtime.Interopservices.Marshal]::ReleaseComObject($workbook) | Out-Null
        }
        if ($excel) {
            [System.Runtime.Interopservices.Marshal]::ReleaseComObject($excel) | Out-Null
        }

        # 清理PowerShell中的COM对象
        [System.GC]::Collect()
        [System.GC]::WaitForPendingFinalizers()
    }
}

$filepath = "E:\WPSDrive\300657811\WPS云盘\党建2024年\花名册-海澜社区(使用excel对党员进行管理)2024年12月.xlsx"
$sheetname = "党员信息"
# 示例调用
$cellData = Get-ExcelCellData -WorkbookPath $filepath -WorksheetName $sheetname -Row 5 -Column 5
Write-Output "The value in cell A1 is: $cellData"